// export const baseurl = "https://pyg.subit.org.cn";
export const baseurl = "http://localhost:8080/api";

export type Awaited<T> = T extends Promise<infer U> ? U : T;

const errorHandler = (data: any) => {
  if (data.code !== 10000) {
    if (data.code === 401) return false;
    console.warn(data.data)
    wx.showToast({
      title: data.data,
      icon: 'error',
      duration: 2000
    })
    return false;
  }
  return true;
}

export const promiseGetStorage = (key) => {
  return new Promise((resolve) => {
    wx.getStorage({
      key: key,
      success(res) {
        resolve(res.data);
      },
      fail(res) {
        resolve(undefined);
      }
    });
  });
}

export const promiseSetStorage = (key, value) => {
  return new Promise((resolve) => {
    wx.setStorage({
      key: key,
      data: value,
      success(res) {
        resolve(undefined);
      }
    })
  })
}

export const promiseLogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) resolve(res.code);
        reject(res);
      },
      fail(res) {
        console.error(res);
        reject(res);
      }
    })
  })
}

export const promiseRequest = (url: string, method: 'GET' | 'POST', options: any = {}) => {
  let defaultOptions = {
    header: {},
    data: null,
    toast: true,
  };
  options = {
    ...defaultOptions,
    ...options
  };
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseurl + url,
      data: options.data,
      method: method,
      header: options.header,
      success(res) {
        if (options.toast && errorHandler(res.data) || !options.toast && res.data["code"] === 10000)
          resolve(res.data);
        else
          reject(res.data["data"])
      },
      fail(res) {
        reject(res);
      }
    });
  });
};
